//
//  ViewController.m
//  LottieFilesPreview
//
//  Created by SssssQG on 2021/3/9.
//

#import "ViewController.h"
#import "TableViewCell.h"
#import "LottilePreviewVC.h"
dispatch_queue_t fileWatcher_queue() {
    static dispatch_queue_t as_fileWatcher_queue;
    static dispatch_once_t onceToken_fileWatcher;
    dispatch_once(&onceToken_fileWatcher, ^{
        as_fileWatcher_queue = dispatch_queue_create("fileWatcher.queue", DISPATCH_QUEUE_CONCURRENT);
    });
    
    return as_fileWatcher_queue;
}

@interface ViewController ()

@property (nonatomic, strong)  dispatch_source_t source;

@property (nonatomic, strong) NSArray<NSString *> *fileNameArr;

@property (nonatomic, assign) BOOL isConvenientFinished;

@property (nonatomic, assign) BOOL isFinishedCopy;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 44;
    [self.tableView registerNib:[UINib nibWithNibName:@"TableViewCell" bundle:nil] forCellReuseIdentifier:@"TableViewCell"];
    self.tableView.tableFooterView = [UIView new];
    
    self.isFinishedCopy = YES;  //此标识是监听
        
    self.isConvenientFinished = YES;
    
    [self startMonitorFile];
    
    [self getDocumentsFiles];
}

- (NSString *)getDocumentsPath {
    NSArray *patchs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    // 获取Documents路径
    NSString *documentsDirectory = [patchs objectAtIndex:0];
    NSString *fileDirectory = [documentsDirectory stringByAppendingPathComponent:@"Inbox"];
    return fileDirectory;
}

- (void)getDocumentsFiles {
    self.fileNameArr =[[NSFileManager defaultManager] subpathsOfDirectoryAtPath:[self getDocumentsPath] error:nil];
    NSLog(@"获取文件刷新列表");
    
    dispatch_async(dispatch_get_main_queue(), ^{
        // 通知主线程刷新
        [self.tableView reloadData];
    });
    
}

- (NSArray<NSString *> *)fileNameArr {
    if (!_fileNameArr) {
        _fileNameArr = [NSArray array];
    }
    return _fileNameArr;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.fileNameArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TableViewCell" forIndexPath:indexPath];
    cell.infoLab.text = self.fileNameArr[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    LottilePreviewVC *vc = [[LottilePreviewVC alloc]init];
    vc.filePath = [NSString stringWithFormat:@"%@/%@",[self getDocumentsPath],self.fileNameArr[indexPath.row]];
    vc.fileName = self.fileNameArr[indexPath.row];
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:^{
            
    }];
}


- (void)stopManager {
    
    dispatch_cancel(self.source);
}

- (void)startMonitorFile {  //监听Document文件夹的变化
    
    NSURL *directoryURL = [NSURL URLWithString:[self getDocumentsPath]]; //添加需要监听的目录
    
    int const fd =
    open([[directoryURL path] fileSystemRepresentation], O_EVTONLY);
    if (fd < 0) {
        
        NSLog(@"Unable to open the path = %@", [directoryURL path]);
        return;
    }
    
    dispatch_source_t source =
    dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, fd,
                           DISPATCH_VNODE_WRITE,
                           DISPATCH_TARGET_QUEUE_DEFAULT);
    dispatch_source_set_event_handler(source, ^() {
        unsigned long const type = dispatch_source_get_data(source);
        switch (type) {
            case DISPATCH_VNODE_WRITE: {
                NSLog(@"Document目录内容发生变化!!!");
                if (self.isConvenientFinished) {
                    self.isConvenientFinished = NO;
                    [self getDocumentsFiles];
                }
                break;
            }
            default:
                break;
        }
    });
    
    dispatch_source_set_cancel_handler(source, ^{
        close(fd);
        
    });
    
    self.source = source;
    dispatch_resume(self.source);
}



@end
